﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Weight.Base;
using Weight.Model;
using Dapper;

namespace Weight.Dal
{
    public class DalRight
    {
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Add(RightEntity entity)
        {
            using (IDbConnection conn = SessionFactory.CreateConnection())
            {
                string sql = " insert into Rights (Id,RoleId,Rights)values(@Id,@RoleId,@Rights)";
                return conn.Execute(sql, entity) > 0 ? true:false;
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update(RightEntity entity)
        {
            using (IDbConnection conn = SessionFactory.CreateConnection())
            {
                string sql = " update  Rights set RoleId=@RoleId,Rights=@Rights where Id =@Id";
                return conn.Execute(sql, entity) > 0 ? true : false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(string id)
        {
            using (IDbConnection conn = SessionFactory.CreateConnection())
            {
                string sql = " delete from   Rights  where Id =@Id";
                return conn.Execute(sql, new { Id=id}) > 0 ? true : false;
            }
        }

        /// 根据角色Id获取所有权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public RightEntity GetByRoleId(string roleId)
        {
            using (IDbConnection conn = SessionFactory.CreateConnection())
            {
                string sql = " select * from Rights where RoleId=@roleId";
                return conn.QueryFirstOrDefault<RightEntity>(sql, new { roleId });
            }
        }

        /// <summary>
        /// 查找指定角色下的所有权限
        /// </summary>
        /// <param name="roles"></param>
        /// <returns></returns>
        public IEnumerable<RightEntity> GetRightByRoleName(List<string> roles)
        {
            string sql = " select * from  Rights where RoleId in(select Id from  Role where RoleName in @roles)";
            using(IDbConnection conn = SessionFactory.CreateConnection())
            {
                return conn.Query<RightEntity>(sql, new { roles });
            }
        }
    }
}
